package com.ruoyi.api;

import com.ruoyi.common.constant.ApiConstants;
import com.ruoyi.common.dto.AppController;
import com.ruoyi.common.dto.JwtUtils;
import com.ruoyi.common.utils.RSAUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.message.MessageUntil;
import com.ruoyi.framework.interceptor.annotation.IgnoreAuth;
import com.ruoyi.framework.interceptor.annotation.LoginUserId;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.framework.web.service.DictService;
import com.ruoyi.project.base.userInfo.domain.UserInfo;
import com.ruoyi.project.base.userInfo.service.IUserInfoService;
import com.ruoyi.project.system.dict.domain.DictData;
import com.ruoyi.project.system.dict.service.IDictDataService;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ywh
 * @date 2021/1/21
 * @desc 用户管理
 */
@RestController
@RequestMapping("/api/user")
public class ApiUserController extends AppController {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private DictService dictService;

    /**
     * 获取验证码
     *
     * @param phone
     * @param type  1-注册,2-忘记
     * @return
     */
    @RequestMapping(value = "/obtainCode")
    @IgnoreAuth
    @Transactional
    public Object obtainCode(String phone, String type) {
        ;
        if (StringUtils.isEmpty(phone)) {
            return writeResultFailure("缺少参数传递");
        }
        try {
            if (StringUtils.isNotEmpty(phone)) {    //是否传入手机号
                Pattern p = Pattern.compile("^1[3456789]\\d{9}$");
                Matcher m = p.matcher(phone);
                if (m.matches()) {  //验证手机号格式
                    UserInfo user = userInfoService.checkPhone(phone);
                    if (type.equals("1")) {   //注册
                        if (StringUtils.isNotNull(user)) {
                            return writeResultFailure("手机号被占用");
                        }
                    } else if (type.equals("2")) {  //忘记
                        if (StringUtils.isNull(user)) {
                            return writeResultFailure("用户不存在");
                        }
                    }
                    /*发送短信*/
                    int code = MessageUntil.sendMessage(phone);
                    return writeResultRep(code);
                }
                return writeResultFailure("手机号格式有误");
            } else {
                return writeResultFailure("手机号为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return writeResultFailure("获取失败！");
        }
    }

    /**
     * 校验账号
     *
     * @param accountName
     * @return
     */
    @RequestMapping(value = "/checkName")
    @IgnoreAuth
    @Transactional
    public Object checkName(String accountName) {
        accountName = EmojiParser.removeAllEmojis(accountName);   //去掉表情
        UserInfo user = userInfoService.checkName(accountName);
        if (user != null) {
            return writeResultFailure("账号重复");
        }
        return toResponsMsgSuccess("账号可用");
    }


    /**
     * 用户注册
     */
    @RequestMapping(value = "/register")
    @IgnoreAuth
    @Transactional
    @RepeatSubmit
    public Object register(String phone, String passStr, String accountName) throws Exception {
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(passStr) || StringUtils.isEmpty(accountName)) {
            return writeResultFailure("缺少参数传递");
        }

        try {
            /*手机查询用户*/
            UserInfo user1 = userInfoService.checkPhone(phone);
            if (StringUtils.isNotNull(user1)) {
                return writeResultFailure("手机号被占用");
            }
            accountName = EmojiParser.removeAllEmojis(accountName.trim());   //去掉表情
            UserInfo user2 = userInfoService.checkName(accountName);
            if (user2 != null) {
                return writeResultFailure("账号重复");
            }
            UserInfo userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setAccountName(accountName);
            String decrypt = RSAUtils.decrypt(passStr, ApiConstants.PRIVATE_KEY); //解密前端传递的密文

            //String pasStr = DigestUtils.md5DigestAsHex((accountName + decrypt).getBytes());   //加密存入数据库

            userInfo.setPassword(decrypt);
            userInfoService.insertUserInfo(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return writeResultFailure("系统错误");
        }
        return toResponsMsgSuccess("注册成功");
    }


    /**
     * 用户登录
     */
    @RequestMapping(value = "/login")
    @IgnoreAuth
    public Object login(String inputStr, String passStr) {
        if (StringUtils.isEmpty(inputStr) || StringUtils.isEmpty(passStr)) {
            return writeResultFailure("缺少参数传递");
        }
        inputStr = inputStr.trim();
        UserInfo userInfo = null;
        String decryptStr = "";
        try {
            Pattern p = Pattern.compile("^1[3456789]\\d{9}$");
            Matcher m = p.matcher(inputStr);
            if (m.matches()) {
                userInfo = userInfoService.checkPhone(inputStr);
            } else {
                userInfo = userInfoService.checkName(inputStr);
            }
            if (StringUtils.isNull(userInfo)) {
                return writeResultFailure("账号不存在");
            } else if (!userInfo.getStatus().equals("1")) {
                return writeResultFailure("账号状态异常无法登陆");
            }
            decryptStr = RSAUtils.decrypt(passStr, ApiConstants.PRIVATE_KEY);   //解密前端的密文密码
        } catch (Exception e) {
            e.printStackTrace();
            return writeResultFailure("系统错误");
        }
        if (userInfo.getPassword().equals(decryptStr)) {
            String token = JwtUtils.sign(userInfo.getUserId());
            return writeResultRep(token);
        }
        return writeResultFailure("密码错误");
    }

    /**
     * 用户信息
     */
    @RequestMapping(value = "/selectUserByToken")
    public Object selectUserByToken(@LoginUserId Long userId) {
        UserInfo userInfo = userInfoService.selectUserInfoById(userId);
        return writeResultRep(userInfo);
    }

    /**
     * 用户信息修改
     */
    @RequestMapping(value = "/edit")
    @IgnoreAuth
    public Object edit(UserInfo userInfo) {
        try {
            int i = userInfoService.updateUserInfo(userInfo);
            if (i < 1) {
                return writeResultFailure("操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return writeResultFailure("系统错误");
        }
        return toResponsMsgSuccess("操作成功");
    }


    /**
     * 修改密码
     */
    @RequestMapping(value = "/editPassword")
    public Object editPassword(@LoginUserId Long userId, String passStr, String oldStr) {
        if (StringUtils.isEmpty(passStr) || StringUtils.isEmpty(oldStr)) {
            return writeResultFailure("缺少参数");
        }
        Boolean flag = userInfoService.checkPassword(userId, oldStr);
        if (!flag) {
            return writeResultFailure("原始密码错误");
        }
        try {
            String decrypt = RSAUtils.decrypt(passStr, ApiConstants.PRIVATE_KEY); //解密前端传递的密文
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(userId);
            userInfo.setPassword(decrypt);
            int i = userInfoService.updateUserInfo(userInfo);
            if (i < 1) {
                return writeResultFailure("操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return writeResultFailure("系统错误");
        }
        return toResponsMsgSuccess("操作成功");
    }

    /**
     * 忘记密码
     */
    @RequestMapping(value = "/forgetPassword")
    @IgnoreAuth
    public Object forgetPassword(String phone, String passStr) throws Exception {
        if (StringUtils.isEmpty(passStr) || StringUtils.isEmpty(passStr)) {
            return writeResultFailure("缺少参数");
        }
        UserInfo user = userInfoService.checkPhone(phone);
        if (StringUtils.isNull(user)) {
            return writeResultFailure("无此用户");
        }
        try {
            String decrypt = RSAUtils.decrypt(passStr, ApiConstants.PRIVATE_KEY); //解密前端传递的密文
            user.setPassword(decrypt);
            int i = userInfoService.updateUserInfo(user);
            if (i < 1) {
                return writeResultFailure("操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return writeResultFailure("系统错误");
        }
        return toResponsMsgSuccess("操作成功");
    }

    /*查询教育类型列表*/
    @RequestMapping("/queryLearnTypeList")
    @IgnoreAuth
    public Object queryLearnTypeList() {
        List<DictData> bowTypeList = dictService.getType("learn_type");
        return writeResultRep(bowTypeList);
    }

    /*条件查询用户列表*/
    @RequestMapping("/queryUserList")
    @IgnoreAuth
    public Object queryUserList(UserInfo user) {
        user.setStatus("1");
        List<UserInfo> list = userInfoService.selectUserInfoList(user);
        return writeResultRep(list);
    }

    /*增加学习时长*/
    @RequestMapping(value = "/adStudyTime")
    public Object adStudyTime(@LoginUserId Long userId, Integer minute) {
        if (StringUtils.isNull(minute)){
            return writeResultFailure("缺少参数");
        }
        UserInfo userInfo = userInfoService.selectUserInfoById(userId);
        userInfo.setLearnDuration(userInfo.getLearnDuration() + minute);
        userInfoService.updateUserInfo(userInfo);
        return writeResultRep();
    }

}
